package com.flow.framework.cipher.algorithm;

import com.flow.framework.cipher.algorithm.version.BcryptVersion;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * BCrypt是由Niels Provos和David Mazières设计的密码哈希函数，他是基于Blowfish密码而来的
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/16
 */
@SuppressWarnings("SpellCheckingInspection")
class Bcrypt {

    private static final Object LOCK = new Object();

    private static final Map<BcryptVersion, BCryptPasswordEncoder> VERSION_ENCODER = new ConcurrentHashMap<>(1);

    static String encrypt(BcryptVersion version, String content) {
        return getEncoder(version).encode(content);
    }

    static boolean verify(BcryptVersion version, String content, String encodedContent) {
        return getEncoder(version).matches(content, encodedContent);
    }

    private static BCryptPasswordEncoder getEncoder(BcryptVersion version) {
        BCryptPasswordEncoder encoder = VERSION_ENCODER.get(version);
        if (null == encoder) {
            synchronized (LOCK) {
                encoder = VERSION_ENCODER.get(version);
                if (null == encoder) {
                    encoder = new BCryptPasswordEncoder(version.getVersion());
                    VERSION_ENCODER.put(version, encoder);
                }
            }
        }
        return encoder;
    }
}
